/*
 * Copyright 2012 Banaanvraag.
 *
 * MIT License, details are found in the LICENSE text file
 */

package banaanvraag.tools.logging;

import java.text.MessageFormat;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

/**
 * Use this Handler when standard output is needed. Only INFO and WARNING and
 * higher are displayed.
 * @author Wukl
 */
public class LogHandler extends Handler {

    long startTime, publishTime;
    MessageFormat form;
    
    /**
     * Create a new LogHandler for general purpose output
     */
    public LogHandler() {
        startTime = System.currentTimeMillis();
    }
    
    @Override
    public void publish(LogRecord record) {
        form = new MessageFormat(record.getMessage());
        
        publishTime = record.getMillis() - startTime;
        if(record.getLevel() == Level.INFO) {
            System.out.println("[" + publishTime + "] " + record.getLevel()
                    .getName() + ": " + form.format(record.getParameters()));
        }
        else if(record.getLevel().intValue() >= Level.WARNING.intValue()) {
            System.out.println("\u001B[31m[" + publishTime + "] " + record
                    .getLevel().getName() + ": " + form.format(record.getParameters()));
            System.exit(1);
        }
    }

    @Override
    public void flush() {}

    @Override
    public void close() throws SecurityException {}
    
}